<template>
  <div>
    <sunSearch :search="searchList" />
    <el-card class="sun-el-card">
      <el-table
        v-loading="loading"
        :data="list"
        element-loading-text="数据加载中..."
        border
        fit
        highlight-current-row
        :header-cell-style="{color:'#000000'}"
      >
        <el-table-column align="center" :width="60" :render-header="renderHeader">
          <template slot-scope="{row}">
            <el-checkbox v-model="row.checked" @change="handleCheckedCitiesChange($event, row)" />
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="file_name" :width="160" />
        <el-table-column label="链接" prop="file_path" />
        <el-table-column align="center" label="大小" prop="size" :width="80">
          <template slot-scope="{row}">
            <span>{{ (row.size / Math.pow(1024, 2)).toFixed(2) }}M</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="创建时间" prop="created_at" :width="170" />
      </el-table>
      <pagination v-show="laypage.total>0" :total="laypage.total" :page.sync="laypage.number" :limit.sync="laypage.size" @pagination="requestData" />
    </el-card>
  </div>
</template>
<script>
import SunSearch from '@/sun-components/SunSearch'
import { get } from '@/api/request'
import { mapGetters } from 'vuex'
import Pagination from '@/sun-components/Pagination'
export default {
  name: 'ProcessCommonEvaluationDataBank',
  components: {
    Pagination,
    SunSearch
  },
  props: {
    source: {
      type: String,
      default: ''
    },
    dataBankFile: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      loading: false,
      searchList: [
        { 'file_name': '名称', type: 'input', show: 'file_name', value: '' }
      ],
      searchFilter: {},
      list: [],
      laypage: {
        number: 1,
        size: 10,
        total: 0
      },
      reserveSelection: {},
      isindeterminate: false, // 选中未全选
      checkedAll: false // 全选
    }
  },
  computed: {
    ...mapGetters([
      'publicRoute'
    ]),
    show_dataBank() {
      return this.$parent.$parent.show_dataBank
    }
  },
  watch: {
    show_dataBank: {
      handler: function(show) {
        if (show) {
          this.requestData()
        }
      }
    }
  },
  created() {
    if (this.show_dataBank) {
      this.requestData()
    }
  },
  methods: {
    renderHeader(h) {
      return (
        <el-checkbox indeterminate={this.isindeterminate} v-model={ this.checkedAll } disabled={this.dataBankFile.multiple === 'radio' } onChange={(e) => this.handleCheckAllChange(e)}></el-checkbox>
      )
    },
    async searchResult(filter) {
      this.searchFilter = filter
      this.reserveSelection = {}
      this.isindeterminate = false
      this.checkedAll = false
      this.requestData()
    },
    async requestData() {
      const _that = this
      _that.loading = true
      await get(`files`, { ...this.searchFilter, ...this.dataBankFile, 'page[size]': this.laypage.size, 'page[number]': this.laypage.number }).then(response => {
        if (response.code === 0) {
          if (response.data) {
            response.data.forEach((item) => {
              item['checked'] = false
              if (_that.reserveSelection[_that.laypage.number]) {
                _that.reserveSelection[_that.laypage.number].forEach(el => {
                  if (item.id === el.id) {
                    item['checked'] = true
                  }
                })
                _that.setChecked()
              } else {
                _that.reserveSelection[_that.laypage.number] = []
              }
            })
            _that.list = response.data
            _that.laypage.total = response.meta.total
          }
        }
        _that.loading = false
      })
    },
    // 全选
    async handleCheckAllChange(checked) {
      const _that = this
      this.list.forEach((item) => {
        item.checked = checked
        if (checked) {
          _that.reserveSelection[_that.laypage.number].push(item)
        } else {
          _that.reserveSelection[_that.laypage.number] = []
        }
      })
      _that.setChecked()
    },
    // 单选
    async handleCheckedCitiesChange(checked, row) {
      const _that = this
      _that.list.forEach((item) => {
        if (this.dataBankFile.multiple === 'radio') {
          if (checked) {
            if (row.id === item.id) {
              item.checked = true
              _that.reserveSelection = {
                [_that.laypage.number]: [row]
              }
            } else {
              item.checked = false
            }
          }
          if (!checked) {
            item.checked = false
            _that.reserveSelection = {}
          }
        }
        if (this.dataBankFile.multiple === 'checkbox' && row.id === item.id) {
          item.checked = checked
          if (checked) {
            _that.reserveSelection[_that.laypage.number].push(row)
          } else {
            _that.reserveSelection[_that.laypage.number].splice(_that.reserveSelection[_that.laypage.number].findIndex(item => item.id === row.id), 1)
          }
        }
      })
      _that.setChecked()
    },
    async setChecked() {
      const _that = this
      let selectionList = []
      const keys = Object.keys(_that.reserveSelection)
      keys.forEach(item => {
        selectionList = [...selectionList, ..._that.reserveSelection[item]]
      })
      _that.$parent.$parent.reserveSelection = selectionList // 最终需要的数据
      if (!_that.reserveSelection[_that.laypage.number]) return // 防止单选取消时报错
      if (_that.reserveSelection[_that.laypage.number].length) {
        _that.isindeterminate = true
        _that.checkedAll = false
      }
      if (_that.reserveSelection[_that.laypage.number].length === _that.list.length) {
        _that.isindeterminate = false
        _that.checkedAll = true
      }
      if (!_that.reserveSelection[_that.laypage.number].length) {
        _that.isindeterminate = false
        _that.checkedAll = false
      }
    }
  }
}
</script>
